<template>
  <contextHolder />
  <Dropdown :trigger="['click']" @openChange="openChange">
    <a
      :style="{
        display: 'inline-flex',
        alignItems: 'center',
        fontWeight: props.actionType === 'top' ? '' : 700,
        color: props.actionType === 'top' ? '' : '#006be6',
      }"
      @click="clickAction"
    >
      <span v-if="loading && props.actionType === 'right'" class="icon-[line-md--loading-loop]" style="margin-right: 5px;"></span>
      <span>操作</span>
      <span v-if="flag" class="icon-[bytesize--chevron-bottom]" style="margin-left: 4px;"></span>
      <span v-else class="icon-[teenyicons--right-outline]" style="margin-left: 4px;"></span>
    </a>
    <template #overlay>
      <Menu v-if="allAction.length > 0" :mode="'vertical'">
        <div v-for="(item, index) in allAction" :key="index">
          <MenuItem
            @click="clickMenu(item)"
            :disabled="item.disabled"
            v-if="!item.children || item.children.length === 0"
          >
            <a style="display: inline-flex; align-items: center">
              <span :class="item.icon" style="margin-right: 5px;"></span>
              {{ item.name }}
            </a>
          </MenuItem>
          <MenuDivider v-if="(index + 2) % 2 === 0" />
        </div>
        <template v-for="(item, index) in allAction" :key="'sub-' + index">
          <SubMenu
            v-if="item.children && item.children.length > 0"
            :title="item.name"
            :disabled="item.disabled"
          >
            <template v-for="(subItem, subIndex) in item.children" :key="'subitem-' + subIndex">
              <MenuItem
                @click="clickMenu(subItem)"
                :disabled="subItem.disabled"
              >
                <a style="display: inline-flex; align-items: center">
                  <span :class="subItem.icon" style="margin-right: 5px;"></span>
                  {{ subItem.name }}
                </a>
              </MenuItem>
            </template>
          </SubMenu>
        </template>
      </Menu>
    </template>
  </Dropdown>
</template>

<script lang="ts" setup>
  import { Dropdown, Menu, MenuItem, MenuDivider, message, Modal, SubMenu } from "ant-design-vue";
  import { ref, defineProps, defineEmits, h } from "vue";
  import { useRouter } from 'vue-router';
  import { getAllTree } from '#/api';
  import { deleteByIds } from "#/api";
  import type { ActionProp } from "../../utils/declar";
  import { handleUpdate, handleDelete } from '../../utils/actionMethod'; // 引入 handler 方法


  const props = defineProps({
    className: {
      type: String,
      required: true,
    },
    rowData: {
      type: Object,
      required: true,
    },
    actionType: {
      type: String,
      required: true,
      validator: (value: string) => ['top', 'right'].includes(value),
    },
    customType: {
      type: String,
      default: "add",
      validator: (value: string) => ['replace', 'add'].includes(value),
    },
    customTopActions: {
      type: Array as () => Array<ActionProp>,
      default: () => [],
    },
    customRightActions: {
      type: Array as () => Array<ActionProp>,
      default: () => [],
    },
    actionApiGet: {
      type: Boolean,
      default: false,
    },
  });

  const emit = defineEmits(['doAction']);
  const router = useRouter();

  const [modal, contextHolder] = Modal.useModal();
  modal.centered = true;

  const flag = ref<boolean>(false);
  const loading = ref<boolean>(false);
  const allAction = ref<ActionProp[]>([]);

  // 默认操作按钮配置
  const defaultTopActions : ActionProp[] = [
    {
      icon: 'icon-[icon-park-outline--update-rotation]',
      name: '编辑',
      actionType:"top",
      key: 'update',
      handler: handleUpdate,
    },
    {
      icon: 'icon-[material-symbols--delete-outline-rounded]',
      name: '删除',
      actionType:"top",
      key: 'delete',
      handler: (rowData) => handleDelete(rowData, props.actionType, props.rowData, emit),
    },
  ];

  const defaultRightActions : ActionProp[] = [
    {
      icon: 'icon-[icon-park-outline--update-rotation]',
      name: '编辑',
      actionType:"top",
      key: 'update',
      handler: handleUpdate,
    },
    {
      icon: 'icon-[material-symbols--delete-outline-rounded]',
      name: '删除',
      actionType:"top",
      key: 'delete',
      handler: (rowData) => handleDelete(rowData, props.actionType, props.rowData, emit),
    },
  ];

  const clickMenu = (param) => {
    console.log("param",param)
    if (props.actionType === 'top' && props.rowData instanceof Set && param.dataValidation) {
      if (props.rowData.size === 0) {
        allAction.value = [];
        message.warn("请先选中数据");
        return;
      }
    }
    const action = allAction.value.find(a => a.key === param.key);
    if (action && action.handler) {
      action.handler(props.rowData);
    } else {
      message.error('未定义的操作');
    }
  };

  const clickAction = () => {
    console.log("props.actionApiGet",props.actionApiGet)
    if (!props.actionApiGet) {
      // 如果没有传入 customActions，则使用默认的按钮配置
      if(props.actionType==='top'){
        allAction.value = props.customType === 'add'? [...defaultTopActions,...props.customTopActions] : props.customTopActions;
        console.log("llAction.value,allAction.",allAction.value)
      } else {
        allAction.value = props.customType === 'add'? [...defaultRightActions,...props.customRightActions] : props.customRightActions;
      }
      return;
    }
    if (allAction.value.length === 0) {
      fetchMenuItems();
    }
  };

  const openChange = (open) => {
    flag.value = open;
  };

  const fetchMenuItems = async () => {
    loading.value = true;
    try {
      let params;
      console.log("props.rowData.pid",props.className)
      if (props.actionType === 'right') {
        params = {
          className: "com.gumo.entity.ActionMenu",
          params: { pid: props.rowData.pid, actionType: 'right' },
        };
      } else {
        params = {
          className: "com.gumo.entity.ActionMenu",
          params: { pidList: Array.from(["PR:"+props.className+":1"]), actionType: 'top' },
        };
      }
      const response = await getAllTree(params);
      allAction.value = response;
      if (allAction.value.length === 0||Object.keys(allAction.value).length === 0) {
        console.log("allAction.value",Object.keys(allAction.value).length)
        message.warn("未定义任何操作按钮哦！")
        return;
      }
    } catch (error) {
      console.error("获取菜单失败：", error);
      message.error("获取菜单失败，请稍后再试");
    } finally {
      loading.value = false;
    }
  };
</script>
